/**
 * 认证相关API接口
 */

import { apiClient } from './http-client'
import { ApiResponse, LoginRequest, LoginResponse, RegisterRequest, RegisterResponse, API_ENDPOINTS } from '../types/api'

/**
 * 用户登录
 * @param credentials 登录凭据
 * @returns Promise<ApiResponse<LoginResponse>>
 */
export const login = async (credentials: LoginRequest): Promise<ApiResponse<LoginResponse>> => {
  return await apiClient.post<LoginResponse>(
    API_ENDPOINTS.LOGIN,
    credentials
  )
}

/**
 * 用户注册
 * @param registerData 注册数据
 * @returns Promise<ApiResponse<RegisterResponse>>
 */
export const register = async (registerData: RegisterRequest): Promise<ApiResponse<RegisterResponse>> => {
  return await apiClient.post<RegisterResponse>(
    API_ENDPOINTS.REGISTER,
    registerData
  )
}

/**
 * 验证token有效性
 * @param token JWT token
 * @returns Promise<ApiResponse<boolean>>
 */
export const validateToken = async (token: string): Promise<ApiResponse<boolean>> => {
  // 设置Authorization header
  apiClient.setAuthToken(token)
  
  try {
    const response = await apiClient.get<boolean>('/api/auth/validate')
    return response
  } catch (error) {
    // 如果验证失败，清除token
    apiClient.clearAuthToken()
    throw error
  }
}

/**
 * 获取当前用户信息
 * @returns Promise<ApiResponse<UserProfileResponse>>
 */
export const getUserProfile = async (): Promise<ApiResponse<any>> => {
  return await apiClient.get<any>('/api/users/profile')
}

/**
 * 登录API接口对象
 */
export const authApi = {
  login,
  register,
  validateToken,
  getUserProfile,
}